package com.demo.modules.sys.form;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.common.base.entity.PageQueryEntity;
import com.demo.common.constant.Constant;
import com.demo.modules.sys.entity.SysMenuEntity;
import com.demo.modules.sys.entity.SysUserEntity;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;

@Getter
@Setter
public class SysMenuQueryForm extends PageQueryEntity {

    /**
     * 查询条件
     */
    public static LambdaQueryWrapper<SysMenuEntity> getQueryWrapper(SysMenuQueryForm params) {
        return new QueryWrapper<SysMenuEntity>()
                .lambda()
                .inSql(getUser().getId() != Constant.SUPER_ADMIN, SysMenuEntity::getId, StrUtil.format("select rm.menu_id from sys_role_menu rm join sys_user_role ur on rm.role_id = ur.role_id where ur.user_id={}", getUser().getId()))
                .orderByAsc(SysMenuEntity::getOrderNum);
    }

    protected static SysUserEntity getUser() {
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            throw new UnauthenticatedException("需要登录");
        }
        return (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
    }
}
